<?php


namespace app\admin\controller;

use app\admin\model\SystemAdmin;
use app\admin\model\WxUserReview;
use app\admin\service\ExcelService;
use app\admin\service\SmsService;
use app\admin\service\TmpMessageService;
use app\admin\traits\Curd;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use app\common\service\CommonService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\App;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\annotation\ControllerAnnotation;
use think\facade\Db;
use think\Model;
use function GuzzleHttp\Psr7\str;

/**
 * @package app\admin\controller
 * @ControllerAnnotation(title="用户管理")
 */
class User extends AdminController
{

    use Curd;

    protected $relationSearch = false;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\User();
        $this->assign('userType',$this->admin['type']);
    }

    /**
     * @NodeAnotation(title="用户列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            if($this->admin['type']==3){
                $where[]=['township','=',$this->admin['area_id']];
            }
            $count = $this->model->where($where)->count();
            $list = $this->model->where($where)->page($page, $limit)->order('status desc,create_time desc')->select();
            foreach ($list as $k=>$v){
                $list[$k]=$this->resetInfo($v);
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign([
            'userStatusSelect'=>json_encode(CommonService::getUserStatus(),true),
        ]);
        return $this->fetch();
    }

    /**
         * @NodeAnotation(title="修改用户")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [

            ];
            $this->validate($post, $rule);
            if (isset($row['password'])) {
                unset($row['password']);
            }
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign([
            'id'          => $id,
            'row'         => $row,
        ]);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="设置密码")
     */
    public function password($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }
            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    private function resetInfo($data){
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]=empty($v)?'':$v;
            }
            $data['last_login_time'] = date('Y-m-d H:i:s',$data['last_login_time']);
            $data['status_text']= CommonService::getUserStatus()[$data['status']] ?? '';
        }
        return $data;
    }

    private function resetExportInfo($data){
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]=empty($v)?'':$v;
            }
            $nickNameStart=substr($data['nick_name'],0,1);
            if($nickNameStart=='='){
                $data['nick_name']=' '.$data['nick_name'];
            }
        }
        return $data;
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export(){
        $excelService=new ExcelService();
        $post=input();
        $where=$excelService->getWhere($post);
        $where[]=['township','=',$this->admin['area_id']];
        $fieldArr=[
            'id'=>'ID','nick_name'=>'昵称','username'=>'登录账户'
        ];
        $list=$this->model->where($where)->order('id desc')->field(array_keys($fieldArr))->select()->toArray();
        foreach ($list as $k=>$v){
            $v=$this->resetExportInfo($v);
            $list[$k]=array_values($v);
        }
        $spreadsheet=new Spreadsheet();
        $activeSheet=$spreadsheet->getActiveSheet();
        $excelService->setSheetTitle($activeSheet,'用户列表');
        $excelService->setSheetHeader($activeSheet,array_values($fieldArr));
        $excelService->setSheetContent($activeSheet,$list,$spreadsheet);
        return true;
    }
}